import { getCookie, setCookie } from '@/utils/browser/cookie'
import dayjs from 'dayjs'
import mqtt from '@/api/mqtt'
import { useUserStore } from '@/store/modules/user'
import { currentTime } from '@/composables/useCurrentTime'
import { getHuoQuQuYu } from '@/api/shengChanSheZhi'
import {
  getDangQianBanCi,
  getbanCi,
  getbanCi_qy,
  type GetBanCiResult,
  getJiTaiTheGongYi,
  getHuoQuDuiYingSheBeiXinXi_qy,
  getgongYiBanCiGetWuLiaoList,
  getHuoQuShuoYouZaiFangPingZhong_qy
} from '@/api/gongGongChaXun'

/**
 * 将旧系统表格列配置提取成vxe配置
 * 直接使用后复制打印出的json
 */
function convertToVxeColumns(originalColumns) {
  return originalColumns.map((column) => {
    const vxeColumn: BasicGridColumnProps = {
      title: column.title,
      field: column.key
    }

    // 处理宽度：优先使用 minWidth，若没有则用 width 转换为 minWidth
    if (column.minWidth !== undefined) {
      vxeColumn.minWidth = column.minWidth
    } else if (column.width !== undefined) {
      vxeColumn.minWidth = column.width
    }

    if (column.fixed) {
      vxeColumn.fixed = column.fixed
    }

    if (column.show === false) {
      vxeColumn.visible = false
    }

    if (column.align !== 'center') {
      vxeColumn.align = column.align
    }

    return vxeColumn
  })
}
// const data = []
// console.log(convertToVxeColumns(data))

/** 获取系统常量 */
export const getSycConstant = <K extends keyof SysConstants>(key: K): SysConstants[K] => {
  const userStore = useUserStore()
  return userStore.getSycConstant(key)
}

/** 是否有区域 */
export const isQuYu = computed(() => getSycConstant('quYuNum') == '1')

/** 获取区域选项列表 */
export const getQuYuOptions = async () => {
  // 先从接口拿 后续考虑缓存
  return await getHuoQuQuYu().then((res) =>
    res.map((v) => ({ ...v, label: v.areaName, value: v.areaId }))
  )
}

/** 获取物料 */
export const getWuLiaoOptions = async (
  params: {
    areaId: string
    craftNodeName: string
    tsidStart: string | number
    tsidEnd: string | number
  },
  options: {
    /** 是否是区域 */
    isQy?: boolean
  } = { isQy: false }
) => {
  if (options.isQy) {
    return await getHuoQuShuoYouZaiFangPingZhong_qy(params).then((res) => {
      return res.map((v) => ({ ...v, label: v.materialName, value: v.materialId }))
    })
  } else {
    return await getgongYiBanCiGetWuLiaoList(params).then((res) => {
      return res.map((v) => ({ ...v, label: v.materialName, value: v.materialId }))
    })
  }
}

/** 获取工序机台 */
export const getGongXuJiTaiOptions = async (
  params: { areaId: string; craftNodeId: string },
  options: {
    /** 是否是区域 */
    isQy?: boolean
  } = { isQy: false }
) => {
  // 先从接口拿 后续考虑缓存
  if (options.isQy) {
    return await getHuoQuDuiYingSheBeiXinXi_qy(params).then((res) => {
      return res.map((v) => ({ ...v, label: v.machineName, value: v.id }))
    })
  }

  // 先从接口拿 后续考虑缓存
  return await getJiTaiTheGongYi(params.craftNodeId).then((res) => {
    return res.map((v) => ({ ...v, label: v.machineName, value: v.id }))
  })
}

/**
 * 拆分班次id 获取时间
 * shiftOptionsLength: 根据班次长度判断是否需要返回班次名称 2: 早晚 3: 早中晚
 */
export const splitTsIdToTime = (tsIdString: number | string, shiftOptionsLength?: number) => {
  const str = tsIdString + ''
  if (str.length === 4) {
    const nian = '20' + tsIdString.toString().substr(0, 2)
    const yue = tsIdString.toString().substr(2, 2)
    return nian + '-' + yue
  } else {
    const nian = '20' + tsIdString.toString().substr(0, 2)
    const yue = tsIdString.toString().substr(2, 2)
    const ri = tsIdString.toString().substr(4, 2)
    const banci = tsIdString.toString().substr(6, 2)
    let ban = ''
    if (banci === '01') {
      ban = '早'
    } else if (banci === '02') {
      if (shiftOptionsLength === 2) {
        ban = '晚'
      } else {
        ban = '中'
      }
    } else if (banci === '03') {
      ban = '晚'
    }
    return nian + '-' + yue + '-' + ri + (shiftOptionsLength ? ' ' + ban : '')
  }
}

/** 根据时间和班次顺序还原班次id */
export const restoreTsId = (timeStr: string, shiftOrder: string) => {
  return timeStr.replace(/-/g, '').slice(2) + shiftOrder
}

/**
 * 计算上一个班号（循环计算）
 * @param currShiftNum 当前班号
 * @param shiftOptionsLength 总班号数（shiftOptions的长度）
 * @returns 上一个班号
 */
const getLastShiftNum = (currShiftNum: string | number, shiftOptionsLength: number): number => {
  // 计算上一个班号
  return ((Number(currShiftNum) - 2 + shiftOptionsLength) % shiftOptionsLength) + 1
}

/** 根据工序获取当前班次信息与上一个班次信息 供查询组件使用 */
export const getCurrentAndLastBanCi = async (
  // params: { craftNodeId?: string; areaId?: string },
  /** 工序id或者区域id */
  id: string,
  options: {
    /** 是否是区域 */
    isQy?: boolean
    /** 是否获取上一个班次 */
    isGetLast?: boolean
  } = { isQy: false, isGetLast: false }
) => {
  const isGetLast = options.isGetLast

  let shiftOptions: (GetBanCiResult & LabelValueOption)[]
  if (options.isQy) {
    shiftOptions = (
      await getbanCi_qy({
        areaId: id,
        start: currentTime.value.format('YYYY-MM-DD HH:mm')
      })
    ).map((v) => ({ ...v, label: v.shiftName, value: v.shiftOrder }))
  } else {
    // 获取班次列表
    shiftOptions = (
      await getbanCi({
        craftNodeId: id,
        start: currentTime.value.format('YYYY-MM-DD HH:mm')
      })
    ).map((v) => ({ ...v, label: v.shiftName, value: v.shiftOrder }))
  }

  // 获取班次信息 分当前班次和上一个班次
  const banCiInfo = await getDangQianBanCi({ craftNodeId: id }).then((res) => {
    const time = splitTsIdToTime(isGetLast ? res.tsIdLast : res.tsId)
    const shiftName = isGetLast ? res.shiftNameLast : res.shiftName
    const tsId = isGetLast ? res.tsIdLast : res.tsId

    // 计算所需班号
    const shiftNum =
      '0' + (isGetLast ? getLastShiftNum(res.shiftNum, shiftOptions.length) : res.shiftNum)

    // 有开始和结束, 默认都是一个班次
    return {
      _originalData: res,
      currTime: time,
      currShiftNum: shiftNum,
      startTime: time,
      startShiftNum: shiftNum,
      startShiftName: shiftName,
      startTsId: tsId,
      endTime: time,
      endShiftNum: shiftNum,
      endShiftName: shiftName,
      endTsId: tsId
    }
  })

  return { banCiInfo, shiftOptions }
}

export const zhuanTai: any = {}
/**
 *  根据index和gongXu（工序）返回对应的状态字符串
 */
zhuanTai.text = (index, gongXu) => {
  // 定义状态映射表
  const statusMap = {
    0: () => {
      const specialStatus = {
        络筒: '落筒',
        条卷: '换卷',
        滤尘: '停车',
        细纱: '落纱',
        粗纱: '落纱'
      }
      return specialStatus[gongXu] || '换桶'
    },
    1: () => (gongXu === '滤尘' ? '开车' : '运行'),
    2: () => '中途停车',
    3: () => (gongXu === '滤尘' ? '通讯异常' : '中途停车'),
    4: () => '电气故障停车',
    5: () => '离线',
    6: () => '了机停车',
    7: () => '初始化状态',
    8: () => '断电停车',
    10: () => '保全保养停车',
    12: () => '计划内停车',
    14: () => '织机经停',
    16: () => '织机纬停'
  }

  // 检查索引是否存在映射
  if (index in statusMap) {
    return statusMap[index]()
  }

  // 默认返回值（可根据需求调整）
  return '未知状态'
}

/**
 *  根据index 返回对应的颜色字符串
 */
zhuanTai.color = (index) => {
  // 定义颜色映射表
  const colorMap = {
    1: '#0BC15E', // 绿色：运行状态
    3: '#ADADAD', // 灰色：通讯异常/离线/初始化状态
    4: '#FF9900', // 橙色： 故障
    5: '#ADADAD',
    7: '#ADADAD'
  }

  // 使用空值合并操作符处理未定义或null的情况
  const normalizedIndex = index ?? null

  // 检查是否存在映射或为空值
  return colorMap[normalizedIndex] || '#FF2A2A' // 红色：默认异常状态
}

/**
 * 根据index 返回对应的工作状态
 */
zhuanTai.gongZuoZhuangTai = (index) => {
  // 定义状态映射表
  const statusMap = {
    0: '初始',
    1: '未定义',
    2: '开关断开',
    3: '保养',
    4: '筒纱更换',
    5: '生产',
    6: '故障',
    7: '停止',
    8: '落纱',
    9: '刹停',
    10: 'ASSEMBLY'
  }

  // 返回映射值或默认文本
  return statusMap[index] || '未知状态'
}

/**
 * 根据index 返回对应的状态颜色
 */
zhuanTai.gongZuoZhuangTaiColor = (index) => {
  // 定义颜色映射表
  const colorMap = {
    5: '#42bb57', // 5 绿色：生产状态
    1: '#41bde1', // 1 浅蓝色：未定义状态
    8: '#809e1a', // 8,0,9,4 橄榄绿：落纱/初始/刹停/筒纱更换状态
    0: '#809e1a',
    9: '#809e1a',
    4: '#809e1a',
    7: '#d63b0b', // 7,2 红色：停止/开关断开状态
    2: '#d63b0b',
    3: '#f57d14', // 3,6 橙色：保养/故障状态
    6: '#f57d14'
  }

  // 返回映射值或默认颜色（灰色）
  return colorMap[index] || '#979393'
}

/** 小数保留两位 */
export const valueZhuaneFloat = (dict, number = 2) => {
  const a = /[a-z]/i
  for (const valKey in dict) {
    if (String(dict[valKey]).indexOf('.') > -1 && a.test(dict[valKey]) !== true) {
      dict[valKey] = +parseFloat(dict[valKey]).toFixed(number)
    }
  }
  return dict
}

export const mqtt_browse_send = function (pageId, page) {
  const pageStr: any = getCookie('shangPage')
  const pageDict: any = getCookie('mqtt_xx')
  if (pageStr !== null && pageStr !== undefined && pageDict !== null && pageDict !== undefined) {
    const data = {
      ...pageDict,
      timestamp: dayjs(pageStr.startTime).format('YYYY-MM-DD HH:mm:ss'),
      eventType: 'browse',
      eventData: {
        duration: dayjs().diff(pageStr.startTime),
        pageId: '' + pageStr.pageId,
        page: '' + pageStr.page
      }
    }
    // setTimeout(function(){
    if (pageStr !== undefined && pageStr.pageId !== undefined) {
      mqtt.ws.send('/exchange/RemoteAndEsystem/EventTracking', {}, JSON.stringify(data))
    }
    // }, 1000);
  }

  const item: any = {
    startTime: dayjs(),
    pageId: pageId,
    page: page
  }
  setCookie('shangPage', item, 0)
}

export const hexToRgba = (hex, opacity) => {
  let rgbaColor = ''
  const reg = /^#[\da-f]{6}$/i
  if (reg.test(hex)) {
    rgbaColor = `rgba(${parseInt('0x' + hex.slice(1, 3))},${parseInt(
      '0x' + hex.slice(3, 5)
    )},${parseInt('0x' + hex.slice(5, 7))},${opacity})`
  }
  return rgbaColor
}

function hslToRgb(H, S, L, num) {
  let R, G, B
  if (+S === 0) {
    R = G = B = L // 饱和度为0 为灰色
  } else {
    const hue2Rgb = function (p, q, t) {
      if (t < 0) t += 1
      if (t > 1) t -= 1
      if (t < 1 / 6) return p + (q - p) * 6 * t
      if (t < 1 / 2) return q
      if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6
      return p
    }
    const Q = L < 0.5 ? L * (1 + S) : L + S - L * S
    const P = 2 * L - Q
    R = hue2Rgb(P, Q, H + 1 / 3)
    G = hue2Rgb(P, Q, H)
    B = hue2Rgb(P, Q, H - 1 / 3)
  }
  return (
    'rgb(' +
    Math.round(R * 255) +
    ',' +
    Math.round(G * 255) +
    ',' +
    Math.round(B * 255) +
    ',' +
    num +
    ')'
  )
}

export const getHslArray = function (number, num = 1) {
  if (number < 10) {
    const colorList = [
      'rgb(246,159,189,1)',
      'rgb(127,154,243,1)',
      'rgb(147,211,60,1)',
      'rgb(118, 16, 219,1)',
      'rgb(246,135,59,1)',
      'rgb(237,109,112,1)',
      'rgb(69,238,229,1)',
      'rgb(51, 154, 240,1)',
      'rgb(19, 176, 109,1)',
      'rgb(163, 131, 75,1)'
    ]
    return colorList.slice(0, number)
  } else {
    const HSL: any = []
    const hslLength = number // 获取数量
    for (let i = 0; i < hslLength; i++) {
      const H = Math.random()
      const S = Math.random()
      const L = Math.random()
      let ret = [H, S, L]

      // 颜色相邻颜色差异须大于 0.25
      if (i > 0 && Math.abs(ret[0] - HSL[i - 1][0]) < 0.25) {
        i--
        continue // 重新获取随机色
      }
      ret[1] = 0.7 + ret[1] * 0.2 // [0.7 - 0.9] 排除过灰颜色
      ret[2] = 0.4 + ret[2] * 0.4 // [0.4 - 0.8] 排除过亮过暗色

      // 数据转化到小数点后两位
      ret = ret.map(function (item) {
        return parseFloat(item.toFixed(2))
      })
      // console.log(111111,hslToRgb(this,ret))
      HSL.push(hslToRgb(ret[0], ret[1], ret[2], num))
    }
    return HSL
  }
}

export const roundNum = function (val, decimals = 2) {
  if (!val && val !== 0) return val
  const factor = Math.pow(10, decimals)
  return Math.round(val * factor) / factor
}
